<template>
  <!-- 工时维护店端-经销商端页面 -->
  <div>
    <!--条件筛选-->
    <TopFilter :list="topFilterList" :cols="3" labelWidth="85" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <!--操作 -->
    <button-area :style="{ paddingLeft: '80px' }"></button-area>
    <!-- 列筛选-->
    <FilterTable
      ref="table"
      columnsRef="repair-labourHour-index"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectData"
    >
      <!--列操作-->
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addEstimate">新增工时</el-button>
        <AjaxButton size="small" type="primary" :click="labourDistributeClick">下发</AjaxButton>
        <AjaxButton size="small" type="primary" :click="batchUpdate.bind(this, true)">批量启用</AjaxButton>
        <AjaxButton size="small" type="primary" :click="batchUpdate.bind(this, false)">批量停用</AjaxButton>
        <el-button size="small" type="primary" icon="el-icon-upload" @click="exportClick">导出模板</el-button>
        <UploadFile style="margin: 0 10px;" :isOnlyButton="true" :limit="99" :actionUrl="`${SERVER.DMSCLOUD_REPAIR}/basedata/repairProject/importRepairItem`" @change="handleUploadChange"
          >Excel导入</UploadFile>
      </template>
    </FilterTable>

    <!--抽屉 -->
    <Drawer :visible.sync="estimate" :title="dialogTitle" :width="1100" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <labourHourInfo :type="handleType" :row="formData" @close="closeEstimate" />
    </Drawer>

    <BaseDialog :visible.sync="showChooseModel" title="车型选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <chooseModel @close="closeChooseModelDialog" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import dictCode from '@/utils/dictCode';
import { exportExcelFile } from '@/utils';
import SERVER from '@/api/server';
import { getSeries } from '@/api/repair/estimateExtension';
import { getLabourHourList, labourDistribute, batchUpdate, importRepairItem, exportRepairItem, getAllUser } from '@/api/repair/repairBusiness/labourHour/index.js';
import labourHourInfo from '@/pages/repair/repairBusiness/labourHour_oem/labourHourInfo';
import chooseModel from '@/pages/repair/repairBusiness/labourHour/chooseModel';
// 延保订单查询
export default {
  name: 'repair-labourHour-index',
  components: { labourHourInfo, chooseModel },
  mixins: [dictionary],
  data() {
    return {
      server: SERVER,
      form: {
        fileList: []
      },
      fetchParams: { xhrAbort: true, dataSources: 10451002 },
      dialogTitle: '',
      fetchApi: getLabourHourList,
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      tableData: [],
      selectFlag: false,
      topFilterList: this.createTopFilterList(),
      estimate: false,
      estimatequery: '',
      showChooseModel: false
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getAllUser();
  },
  methods: {
    async getAllUser() {
      let res = await getAllUser();
      if (res.resultCode === 200) {
        let allUser = res.data.map(x => ({
          text: x.employeeName,
          value: x.userId + ''
        }));
        this.columns.find(x => x.dataIndex === 'createdBy').dictItems = allUser;
        this.columns.find(x => x.dataIndex === 'updateBy').dictItems = allUser;
      }
    },
    // 导入成功事件
    handleUploadChange(e) {
      console.log('导入文件上传成功', e.length);
      if (e.length > 0) {
        this.$notify.success({ title: '提示信息', message: '导入成功!!!' });
        this.fetchParams = Object.assign({}, this.fetchParams);
        // this.loading = false;
      }
    },
    exportClick() {
      exportRepairItem().then(res => {
        exportExcelFile(res.data, '维修项目数据导入模板.xls');
      });
    },
    importClick() {},
    // 批量启用/停用
    async batchUpdate(start) {
      if (!this.tableData.length) {
        this.$notify.error({ title: '提示信息', message: '请至少选择一条数据！！！' });
        return;
      }
      let labourCodes = [];
      this.tableData.forEach(x => {
        labourCodes.push(x.labourCode);
      });

      let res = await batchUpdate(start ? 10031001 : 10031002, labourCodes);
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '操作成功！！' });
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
    async labourDistributeClick() {
      if (!this.tableData.length) {
        this.$notify.error({ title: '提示信息', message: '请至少选择一条数据！！！' });
        return;
      }
      let labourCodes = [];
      this.tableData.forEach(x => {
        labourCodes.push(x.labourCode);
      });
      let res = await labourDistribute(labourCodes);
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '下发成功！！' });
      }
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '工时代码',
          fieldName: 'labourCode',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '工时名称',
          fieldName: 'labourName',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '工时状态',
          fieldName: 'itemStatus',
          placeholder: '请选择...',
          itemList: this.createDictList('1003')
        },
        {
          type: 'SELECT',
          label: '是否技术升级',
          fieldName: 'isUpgrade',
          placeholder: '请选择...',
          itemList: this.createDictList('1004')
        },
        // {
        //   type: 'SELECT',
        //   label: '车系',
        //   fieldName: 'seriesCode',
        //   placeholder: '请选择...',
        //   itemList: []
        // },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modelCode',
          placeholder: '请选择...',
          itemList: [],
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.openModelDialog()}></el-button>
              </div>
            );
          }
        }
        // {
        //   type: 'SELECT',
        //   label: '数据来源',
        //   fieldName: 'dataSources',
        //   placeholder: '请选择...',
        //   initialValue: 10451002,
        //   itemList: this.createDictList('1045')
        // }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          minWidth: '100',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.emitFun(props.row, 'edit')}>
                  编辑
                </el-button>
                <el-button size="mini" type="text" onClick={() => this.emitFun(props.row, 'show')}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '状态',
          dataIndex: 'itemStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1003'),
          render: props => {
            return <span>{this.createDictText(props.row.itemStatus, '1003')}</span>;
          }
        },
        {
          title: '是否下发',
          dataIndex: 'isDown',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          dictItems: this.createDictList('1004')
        },
        // {
        //   title: '数据来源',
        //   dataIndex: 'dataSources',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('1045'),
        //   render: props => {
        //     return <span>{this.createDictText(props.row.dataSources, '1045')}</span>;
        //   }
        // },
        {
          title: '是否技术升级',
          dataIndex: 'isUpgrade',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          dictItems: this.createDictList('1004')
        },
        {
          title: '工时代码',
          dataIndex: 'labourCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '工时名称',
          dataIndex: 'labourName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '适用车型数量',
          dataIndex: 'num',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '创建人',
          dataIndex: 'createdBy',
          width: 150,
          sorter: true
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          width: 150,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true
        },
        {
          title: '修改人',
          dataIndex: 'updateBy',
          width: 150,
          sorter: true
        },
        {
          title: '修改时间',
          dataIndex: 'updateAt',
          width: 150,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          sorter: true
        }
      ];
    },

    emitFun(val, type) {
      this.handleType = type;
      this.dialogTitle = `工时信息`;
      this.formData = val;
      this.estimate = true;
    },

    addEstimate() {
      // 新建
      this.handleType = 'add';
      this.showHandler();
    },
    showHandler() {
      // 显示
      this.dialogTitle = `工时信息`;
      this.estimate = true;
    },
    selectData(val) {
      this.tableData = val;
      if (val.length == 0) {
        this.selectFlag = false;
      } else {
        this.selectFlag = true;
      }
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },

    closeEstimate(val, type) {
      // 关闭
      this.estimate = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeChooseModelDialog(param) {
      this.showChooseModel = false;
      if (param.length) {
        this.topFilterList.find(x => x.fieldName === 'modelCode').initialValue = param[0].modelCode;
      }
      // 判断是否存在重复
      // for (let index = 0; index < param.length; index++) {
      //   const element = param[index];
      //   let result = this.dataSource.find(item => element.modelCode === item.modelCode);
      //   if (result) {
      //     this.$notify.error({ title: '提示信息', message: '添加的数据和已有的车型存在重复' });
      //     return;
      //   }
      // }
      // this.BaseTable.EXECUTE_INSERT(param);
    },
    openModelDialog() {
      this.showChooseModel = true;
    }
  }
};
</script>

<style lang="less" scoped></style>
